<?php declare(strict_types=1);


namespace App\Model\Logic;


use App\Helper\RedisConst;
use App\Model\Entity\LoginLog;
use App\Model\Entity\MemberMerchants;
use App\Model\Entity\Members;
use App\Model\Entity\MemberSwitch;
use App\Model\Entity\SwitchMember;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Redis\Pool;

/**
 * @Bean()
 * Class MemberLogic
 * @package App\Model\Logic
 */
class MemberLogic
{

    /**
     * @Inject()
     * @var FormatDataLogic
     */
    private $formatdata_logic;

    /**
     * @Inject("redis.pool")
     * @var Pool
     */
    private $redis;

    /**
     * @Inject()
     * @var MemberRedisLogic
     */
    private $member_redis;

    public function findOne($condition)
    {
        $data = Members::where($condition)->first()->toArray();
        return $data ? $data : null;
    }


    /**
     * 密码检测
     * @param $account
     * @param $password
     * @param $pwdhash
     * @return bool|int
     */
    public function passwordCheck($account, $password, $pwdhash)
    {
        if(!password_verify($password, $pwdhash)) {
            $key = RedisConst::PASSWORDCHECK_DAILY . md5($account);
            $this->redis->incr($key);
            $this->redis->expire($key, 3600);
            return 10055;
        }
        return true;
    }


    /**
     * 获取普通用户ID上一次使用的登录身份ID
     * @param $member_id
     * @return array|null
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     */
    public function getLastRoleByNormalId($member_id)
    {
        $data = SwitchMember::where('member_id', $member_id)->orderBy('created_at','desc')->first()->toArray();
        if(!$data) return null;
        $exist = MemberMerchants::where('member_id', $member_id)
            ->where('merchants_id', $data['switch_member_id'])
            ->where('status',1)
            ->first();
        if(!$exist) return null;
        $member = $this->member_redis->info($data['switch_member_id']);
        return [
            'type' => config('app.business_conf')[$member['type']],
            'member_id'   => (int)$member['id'],
            'business_id' => (int)$member['type_id'],
        ];
    }




    /**
     * 用户登录返回信息
     * @param $member_id
     * @return mixed
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     * @throws \Swoft\Db\Exception\DbException
     */
    public function memberLoginInfo($member_id)
    {
        $lang = config('app.lang_conf');
        $member_info = $this->member_redis->info($member_id);
        $member['member_name'] = [
            'nickname' => $member_info['nickname'],
            'displayname' => $member_info['displayname'],
            'icon' => $this->formatdata_logic->getMemberIcon($member_info['id']),
        ];
        $role = [
            1 => 'normal',
            2 => 'brand',
            3 => 'shop',
        ];
        $member['review_permission'] = $member_info['review_permission'];
        $member['member_id'] = intval($member_info['id']);
        $member['avatar'] = formatAvatar($member_info['avatar']);
        $member['lang_setting'] = $lang[$member_info['lang_setting']];
        $member['business_id'] = $member_info['type_id'];
        $member['role'] = $role[$member_info['type']];
        $member['member_role_id'] = $member_info['type'];
        $member['member_uuid'] = $member_info['uuid'];
        $member['uuid'] = $member_info['uuid'];
        //消息接收设置
        $msg = MemberSwitch::where('member_id', $member_id)->get()->toArray();
        $value = ['off', 'on'];
        $item  = [
            1 => 'followers',
            2 => 'attention',
            3 => 'like',
            4 => 'comment',
            5 => 'sound',
        ];
        if(!$msg){
            $member['followers'] = $value[1];
            $member['attention'] = $value[1];
            $member['like'] = $value[1];
            $member['comment'] = $value[1];
            $member['sound'] = $value[1];
        } else {
            foreach($msg as $key => $val){
                $member[$item[$val['type']]] = $value[$val['setting']];
            }
            if(!isset($member['sound'])) $member['sound'] = $value[1];
        }
        return $member;
    }


    /**
     * 登录日志
     * @param $member_id
     * @param $ip
     * @param $version
     * @param $device
     * @param $serial_number
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     * @throws \Swoft\Db\Exception\DbException
     */
    public function loginLog($member_id, $ip, $version, $device, $serial_number)
    {
        $equipment = config('app.device_conf');
        $login_log = LoginLog::new();
        $login_log->setMemberId($member_id);
        $login_log->setEquipment($equipment[$device]);
        $login_log->setEquipmentNumber($serial_number);
        $login_log->setCoordinate('');
        $login_log->setLoginIp($ip);
        $login_log->setVersion($version);
        $login_log->setLoginTime(time());
        $login_log->save();
    }

    /**
     * --------------------------------------------------------------------------
     * 获取普通用户名下关联的所有商业级用户列表
     * --------------------------------------------------------------------------
     * @param $normal_member_id
     * @param null $version
     * @param bool|false $format
     * @return array
     */
    public function getBusinessListByNormal($normal_member_id, $version = null, $format =false)
    {
        $option = [
            'member_id' => $normal_member_id,
            'status'    => 1,
        ];
        $business = MemberMerchants::where($option)
            ->where('merchants_id', '!=', $normal_member_id)
            ->pluck('merchants_id')->toArray();
        if(!$business) return [];
        //头像、member_id、类型
        if(!$format) return $business;
        array_push($business, $normal_member_id);
        $data = $this->buildSwitchRoleListById($business, $version);
        return $data;
    }


    /**
     * --------------------------------------------------------------------------
     * 获取指定商业级用户数据
     * --------------------------------------------------------------------------
     * @param $member_ids
     * @param null $version
     * @return array
     */
    public function buildSwitchRoleListById($member_ids)
    {
        if(!is_array($member_ids)) $member_ids = [$member_ids];
        foreach($member_ids as $member_id){
            $data[] = $this->formatdata_logic->buildMemberIcon($member_id);
        }
        return $data;
    }






}